package com.zlz.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlz.server.constant.MailConstant;
import com.zlz.server.mapper.EmployeeMapper;
import com.zlz.server.mapper.MailLogMapper;
import com.zlz.server.pojo.Employee;
import com.zlz.server.pojo.MailLog;
import com.zlz.server.pojo.RespBean;
import com.zlz.server.pojo.RespPageBean;
import com.zlz.server.service.IEmployeeService;
import com.zlz.server.utils.MyStringUtils;
import com.zlz.server.utils.ParamUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author efire
 * @since 2021-01-31
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    public static final String MAX_WORK_ID = "MAX(work_id)";
    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MailLogMapper mailLogMapper;

    @Override
    public RespPageBean getEmployeeByPage(Integer curPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        // 开启分页
        Page<Employee> page = new Page<>(curPage, size);
        employee.setName(ParamUtil.dealSpecialString(employee.getName()));
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
        return new RespPageBean(employeeByPage.getTotal(), employeeByPage.getRecords());
    }

    @Override
    public String getMaxWorkId() {
       List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select(MAX_WORK_ID));
       return String.format("%08d", Long.parseLong(maps.get(0).get(MAX_WORK_ID).toString()) + 1);
    }

    @Override
    public RespBean addEmp(Employee employee) {
        // 处理合同期限
        dealTerm(employee);
        if (1 == employeeMapper.insert(employee)) {
            // 获取员工信息
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);

            // 数据库记录发送消息
            String msgId = MyStringUtils.createUuid();
            MailLog mailLog = MailLog.builder()
                    .msgId(msgId)
                    .eid(emp.getId())
                    .status(0)
                    .count(0)
                    .routeKey(MailConstant.MAIL_ROUTING_KEY_NAME)
                    .exchange(MailConstant.MAIL_EXCHANGE_NAME)
                    .tryTime(LocalDateTime.now().plusMinutes(MailConstant.MSG_TIMEOUT))
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            mailLogMapper.insert(mailLog);


            rabbitTemplate.convertAndSend(MailConstant.MAIL_EXCHANGE_NAME, MailConstant.MAIL_ROUTING_KEY_NAME, emp,
                    new CorrelationData(msgId));
            return RespBean.success("添加成功", null);
        }
        return RespBean.error("添加失败");
    }

    @Override
    public List<Employee> getEmployee(Long id) {
        return employeeMapper.getEmployee(id);
    }

    @Override
    public RespPageBean getEmpsWithSalary(Integer curPage, Integer size) {
        Page<Employee> page = new Page<>();
        IPage<Employee> emps = employeeMapper.getEmpWithSalary(page);
        return new RespPageBean(emps.getTotal(), emps.getRecords());
    }

    private void dealTerm(Employee employee) {
        LocalDate begin = employee.getBeginContract();
        LocalDate end = employee.getEndContract();
        long days = begin.until(end, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
    }
}
